package com.web44.ssm.config;

import com.web44.ssm.interceptor.ErrorInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * @Title: SpringMvcConfig
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/2/18 9:40
 */
@Configuration
@EnableWebMvc
@ComponentScan(value = "com.web44.ssm.web")
public class SpringMvcConfig implements WebMvcConfigurer {

    @Autowired
    private ErrorInterceptor errorInterceptor;

    /**
     * 设置请求匹配映射
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/news").setViewName("news");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * addResourceHandler 访问路径
         * addResourceLocations 本地资源路径
         */
        registry.addResourceHandler("/images/**").addResourceLocations("/images/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
    }

    /**
     * 视图解析器
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setCache(false);
        registry.viewResolver(viewResolver);
    }

    /**
     * 拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(errorInterceptor).addPathPatterns("/**");
    }
}
